<!-- #layout name=blank -->
<div id="app">
  <div class="page-header">
    <h1 class="title">Views</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a
        class="btn green navbar-btn"
        :href="Kooboo.Route.Get(Kooboo.Route.View.Create)"
        >Create</a
      >
      <a
        class="btn green navbar-btn"
        v-show="selectedRows.length==1"
        @click="showCopyModal=true"
        >Copy</a
      >
      <a
        class="btn red navbar-btn"
        v-show="selectedRows.length>0"
        @click="onDelete"
        >Delete</a
      >
    </div>
  </div>
  <kb-table :data="model" show-select :selected.sync="selectedRows">
    <kb-table-column :label="Kooboo.text.common.name">
      <template v-slot="row">
        <a :href="getDetailUrl(row.id)" @click.stop="">{{ row.name }}</a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.usedBy">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                  background: Kooboo.getLabelColor(item.key.toLowerCase())
                }"
          v-for="(item, index) in Kooboo.objToArr(row.relations)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.View.name)"
        >
          {{
            item.value +
              " " +
              Kooboo.text.component.table[item.key.toLowerCase()]
          }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.view.dataSource">
      <template v-slot="row">
        <a
          class="badge blue"
          v-if="row.dataSourceCount"
          @click.stop="onShowDataSourceModal(row.id)"
        >
          {{ row.dataSourceCount }}
        </a>
        <span v-else>-</span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.preview">
      <template v-slot="row">
        <a :href="row.preview" @click.stop="" target="_blank">
          {{ row.preview }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column width="10px">
      <template v-slot="row">
        <a
          class="btn blue btn-xs"
          :href="getVersionsUrl(row.keyHash,row.storeNameHash)"
          @click.stop=""
          target="_blank"
        >
          <i class="fa fa-clock-o"></i>
        </a>
      </template>
    </kb-table-column>
  </kb-table>
  <kb-relation-modal></kb-relation-modal>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showDataSourceModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button @click="showDataSourceModal=false" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">Data Source</h4>
        </div>
        <div class="modal-body">
          <table class="table table-striped table-hover">
            <thead>
              <tr>
                <th>Name</th>
                <th class="table-action">Edit</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in dataSource" :key="index">
                <td>{{ item.aliasName }}</td>
                <td>
                  <a
                    :href="getDataSourceEditUrl(item.methodId)"
                    target="_blank"
                    class="btn btn-xs blue"
                    ><i class="fa fa-pencil"></i
                  ></a>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="modal-footer">
          <button @click="showDataSourceModal = false" class="btn btn-default"
            >OK</button
          >
        </div>
      </div>
    </div>
  </div>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showCopyModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" @click="showCopyModal=false"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">{{ copyModalTitle }}</h4>
        </div>
        <div class="modal-body" v-if="showCopyModal">
          <kb-form :model="copyModel" :rules="copyModelRules" ref="copyForm">
            <kb-form-item prop="name">
              <label class="control-label col-md-3">Name</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="copyModel.name"
                />
              </div>
            </kb-form-item>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button @click="onStartCopy" class="btn green">Start</button>
          <button @click="showCopyModal=false" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbForm.js",
    "/_Admin/Scripts/components/kbTable.js",
    "/_Admin/Scripts/components/kbRelationModal.js"
  ]);
  new Vue({
    el: "#app",
    data: function() {
      var me = this;
      return {
        breads: [
          {
            name: "SITES"
          },
          {
            name: "DASHBOARD"
          },
          {
            name: Kooboo.text.common.Views
          }
        ],
        model: [],
        selectedRows: [],
        showCopyModal: false,
        showDataSourceModal: false,
        dataSource: [],
        copyModel: {
          id: "",
          name: ""
        },
        copyModelRules: {
          name: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^([A-Za-z][\w\-\.]*)*[A-Za-z0-9]$/,
              message: Kooboo.text.validation.objectNameRegex
            },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            },
            {
              remote: {
                url: Kooboo.View.isUniqueName(),
                data: function() {
                  return {
                    name: me.copyModel.name
                  };
                }
              },
              message: Kooboo.text.validation.taken
            }
          ]
        }
      };
    },
    mounted: function() {
      var me = this;
      Kooboo.View.getList().then(function(res) {
        me.model = _.sortBy(res.model, [
          function(r) {
            return r.lastModified;
          }
        ]).reverse();
      });
    },
    computed: {
      copyModalTitle: function() {
        var title = Kooboo.text.site.view.copyView + ": ";
        if (this.selectedRows.length == 1) {
          title += this.selectedRows[0].name;
        }
        return title;
      }
    },
    methods: {
      getDetailUrl: function(id) {
        return Kooboo.Route.Get(Kooboo.Route.View.DetailPage, {
          Id: id
        });
      },
      onShowRelationModal: function(by, id, type) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          by: by,
          type: type,
          id: id
        });
      },
      onShowDataSourceModal: function(id) {
        var me = this;
        Kooboo.View.ViewMethods({
          id: id
        }).then(function(res) {
          if (res.success) {
            me.dataSource = res.model;
            me.showDataSourceModal = true;
          }
        });
      },
      getVersionsUrl: function(keyHash, storeNameHash) {
        return Kooboo.Route.Get(Kooboo.Route.SiteLog.LogVersions, {
          KeyHash: keyHash,
          storeNameHash: storeNameHash
        });
      },
      getDataSourceEditUrl: function(id) {
        return Kooboo.Route.Get(Kooboo.Route.DataSource.DataMethodSetting, {
          isNew: false,
          id: id
        });
      },
      onStartCopy: function() {
        if (this.$refs.copyForm.validate()) {
          var me = this;
          Kooboo.View.Copy(this.copyModel).then(function(res) {
            if (res.success) {
              me.model.push(res.model);
              me.showCopyModal = false;
              window.info.show(Kooboo.text.info.copy.success, true);
            } else {
              window.info.show(Kooboo.text.info.copy.fail, false);
            }
          });
        }
      },
      onDelete: function() {
        var me = this;
        var haveRelations = this.selectedRows.some(function(s) {
          return s.relations && Object.keys(s.relations).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function(m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;

        Kooboo[Kooboo.View.name]
          .Deletes({
            ids: ids
          })
          .then(function(res) {
            if (res.success) {
              Kooboo.View.getList().then(function(res) {
                me.model = _.sortBy(res.model, [
                  function(r) {
                    return r.lastModified;
                  }
                ]).reverse();
              });
              window.info.done(Kooboo.text.info.delete.success);
            } else {
              window.info.done(Kooboo.text.info.delete.fail);
            }
          });
      }
    },
    watch: {
      showDataSourceModal: function(value) {
        if (!value) this.dataSource = [];
      },
      showCopyModal: function(value) {
        if (value && this.selectedRows.length == 1) {
          this.copyModel.id = this.selectedRows[0].id;
          this.copyModel.name = this.selectedRows[0].name + "_Copy";
        }
      }
    }
  });
</script>
